//
//  TYZSystemDialog.m
//  TYZ_SC
//
//  Created by 李贤立 on 2017/12/21.
//  Copyright © 2017年 Capfer. All rights reserved.
//

#import "TYZSystemDialog.h"
#define MostSystemDialogNumber 6
@interface TYZSystemDialog ()<UITextFieldDelegate>
/**
 *  字数上限
 */
@property(nonatomic, assign) NSInteger mostLength;
@end

@implementation TYZSystemDialog
#pragma mark - Dialog
/**
 *  创建系统弹框
 *  默认悬浮中间，显示确认和取消
 *  @pram title      标题
 *  @pram complement 点击确认的回调
 */
+ (instancetype)dialogWithTitle:(NSString *)title complement:(void(^)(void))complement {
    return [self dialogWithViewController:[self getCurrentViewController] title:title complement:complement];
}
+ (instancetype)dialogWithViewController:(UIViewController *)viewController title:(NSString *)title complement:(void(^)(void))complement {
    return [self dialogWithViewController:viewController title:title dialogType:SystemDialogType_Default complement:complement];
}
/**
 *  创建中间悬浮的系统弹框的类型
 *
 *  @pram title      标题
 *  @pram dialogType 弹框类型（只对前五种有效）
 *  @pram complement 点击确认的回调
 */
+ (instancetype)dialogWithTitle:(NSString *)title dialogType:(TYZSystemDialogType)dialogType complement:(void(^)(void))complement {
    return [self dialogWithViewController:[self getCurrentViewController] title:title dialogType:dialogType complement:complement];
}
+ (instancetype)dialogWithViewController:(UIViewController *)viewController title:(NSString *)title dialogType:(TYZSystemDialogType)dialogType complement:(void(^)(void))complement {
    TYZSystemDialog *dialog = [TYZSystemDialog alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleAlert];
    if (dialogType == SystemDialogType_Default) {
        [dialog addAction:[self creatActionWithTitle:[@"取消" S] complement:nil]];
        [dialog addAction:[self creatActionWithTitle:[@"确认" S] complement:complement]];
    } else if (dialogType == SystemDialogType_OneSure) {
        [dialog addAction:[self creatActionWithTitle:[@"确认" S] complement:complement]];
    } else if (dialogType == SystemDialogType_Destructive_Center) {
        [dialog addAction:[self creatActionWithTitle:[@"确认" S] style:UIAlertActionStyleDestructive complement:complement]];
    } else if (dialogType == SystemDialogType_Destructive_Right) {
        [dialog addAction:[self creatActionWithTitle:[@"取消" S] complement:nil]];
        [dialog addAction:[self creatActionWithTitle:[@"确认" S] style:UIAlertActionStyleDestructive complement:complement]];
    } else if (dialogType == SystemDialogType_Destructive_Left) {
        [dialog addAction:[self creatActionWithTitle:[@"取消" S] style:UIAlertActionStyleDestructive complement:nil]];
        [dialog addAction:[self creatActionWithTitle:[@"确认" S] complement:complement]];
    }
    [viewController presentViewController:dialog animated:YES completion:nil];
    return dialog;
}
/**
 *  根据传入的数据创建底部弹出的系统弹框的类型 点击选择第几个选项的回调
 *
 *  @pram title      标题
 *  @pram showData   显示的数据，弹框类型只是第六种，从底部弹出
 *  @pram complement 点击确认的回调
 */
+ (instancetype)dialogWithTitle:(NSString *)title showData:(NSArray<NSString *> *)showData complement:(void(^)(NSInteger index))complement {
    return [self dialogWithViewController:[self getCurrentViewController] title:title showData:showData complement:complement];
}
+ (instancetype)dialogWithViewController:(UIViewController *)viewController title:(NSString *)title showData:(NSArray<NSString *> *)showData complement:(void(^)(NSInteger index))complement {
    TYZSystemDialog *dialog = [TYZSystemDialog alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    NSInteger number = showData.count > MostSystemDialogNumber ? MostSystemDialogNumber : showData.count;
    for (NSInteger i = 0; i < number; i ++) {
        [dialog addAction:[self creatActionWithTitle:showData[i] complement:^{
            if (complement) {
                complement(i);
            }
        }]];
    }
    [dialog addAction:[self creatActionWithTitle:[@"取消" S] style:UIAlertActionStyleCancel complement:nil]];
    [viewController presentViewController:dialog animated:YES completion:nil];
    return dialog;
}
/**
 *  根据自定义传入的中间弹框选择的数据创建系统弹框的类型 点击选择第几个选项的回调
 *
 *  @pram title      标题
 *  @pram showData   显示的数据，弹框类型只是第六种，从底部弹出
 *  @pram dialogType 弹框类型（只对后五种有效）
 *  @pram complement 点击确认的回调
 */
+ (instancetype)dialogWithTitle:(NSString *)title showData:(NSArray<NSString *> *)showData dialogType:(TYZSystemDialogType)dialogType complement:(void(^)(NSInteger index))complement {
    return [self dialogWithViewController:[self getCurrentViewController] title:title showData:showData dialogType:dialogType complement:complement];
}
+ (instancetype)dialogWithViewController:(UIViewController *)viewController title:(NSString *)title showData:(NSArray<NSString *> *)showData dialogType:(TYZSystemDialogType)dialogType complement:(void(^)(NSInteger index))complement {
    TYZSystemDialog *dialog = [TYZSystemDialog alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleAlert];
    if (showData.count == 1) {
        if (dialogType == SystemDialogType_Custem_OneSure) {
            [dialog addAction:[self creatActionWithTitle:showData.firstObject complement:^{
                if (complement) {
                    complement(0);
                }
            }]];
        } else if (dialogType == SystemDialogType_Custem_Destructive_Center) {
            [dialog addAction:[self creatActionWithTitle:showData.firstObject style:UIAlertActionStyleDestructive complement:^{
                if (complement) {
                    complement(0);
                }
            }]];
        }
    } else if (showData.count == 2) {
        if (dialogType == SystemDialogType_Custem_Default) {
            [dialog addAction:[self creatActionWithTitle:showData.firstObject complement:^{
                if (complement) {
                    complement(0);
                }
            }]];
            [dialog addAction:[self creatActionWithTitle:showData.lastObject complement:^{
                if (complement) {
                    complement(1);
                }
            }]];
        } else if (dialogType == SystemDialogType_Custem_Destructive_Left) {
            [dialog addAction:[self creatActionWithTitle:showData.firstObject style:UIAlertActionStyleDestructive complement:^{
                if (complement) {
                    complement(0);
                }
            }]];
            [dialog addAction:[self creatActionWithTitle:showData.lastObject style:UIAlertActionStyleCancel complement:^{
                if (complement) {
                    complement(1);
                }
            }]];
        } else if (dialogType == SystemDialogType_Custem_Destructive_Right) {
            [dialog addAction:[self creatActionWithTitle:showData.firstObject style:UIAlertActionStyleCancel complement:^{
                if (complement) {
                    complement(0);
                }
            }]];
            [dialog addAction:[self creatActionWithTitle:showData.lastObject style:UIAlertActionStyleDestructive complement:^{
                if (complement) {
                    complement(1);
                }
            }]];
        }
    }
    [viewController presentViewController:dialog animated:YES completion:nil];
    return dialog;
}
/**
 *  创建带输入框的非密码形式的弹框
 *
 *  @pram title         标题
 *  @pram placeholder   占位文本
 *  @pram textLength    输入字数上限
 *  @pram isCenter      是否居中
 *  @pram complement    点击确认的回调
 */
+ (instancetype)dialogWithTitle:(NSString *)title placeholder:(NSString *)placeholder textLenth:(NSInteger)textLength isCenter:(BOOL)isCenter complement:(void(^)(NSString *text))complement {
    return [self dialogWithViewController:[self getCurrentViewController] title:title placeholder:placeholder textLenth:textLength isCenter:isCenter complement:complement];
}
+ (instancetype)dialogWithViewController:(UIViewController *)viewController title:(NSString *)title placeholder:(NSString *)placeholder textLenth:(NSInteger)textLength isCenter:(BOOL)isCenter complement:(void(^)(NSString *text))complement {
    return [self dialogWithViewController:viewController title:title placeholder:placeholder textLenth:textLength isCenter:isCenter secureTextEntry:NO complement:complement];
}
/**
 *  创建带输入框的弹框
 *
 *  @pram title             标题
 *  @pram placeholder       占位文本
 *  @pram textLength        输入字数上限
 *  @pram isCenter          是否居中
 *  @pram secureTextEntry   是否是密码模式
 *  @pram complement        点击确认的回调
 */
+ (instancetype)dialogWithTitle:(NSString *)title placeholder:(NSString *)placeholder textLenth:(NSInteger)textLength isCenter:(BOOL)isCenter secureTextEntry:(BOOL)secureTextEntry complement:(void(^)(NSString *text))complement {
    return [self dialogWithViewController:[self getCurrentViewController] title:title placeholder:placeholder textLenth:textLength isCenter:isCenter secureTextEntry:secureTextEntry complement:complement];
}
+ (instancetype)dialogWithViewController:(UIViewController *)viewController title:(NSString *)title placeholder:(NSString *)placeholder textLenth:(NSInteger)textLength isCenter:(BOOL)isCenter secureTextEntry:(BOOL)secureTextEntry complement:(void(^)(NSString *text))complement {
    TYZSystemDialog *dialog = [TYZSystemDialog alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleAlert];
    __weak typeof(dialog) weakDialog = dialog;
    [dialog addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.delegate = weakDialog;
        weakDialog.mostLength = textLength;
        textField.placeholder = placeholder;
        textField.secureTextEntry = secureTextEntry;
        if (isCenter) {
            textField.textAlignment = NSTextAlignmentCenter;
            textField.clearButtonMode = UITextFieldViewModeNever;
        } else {
            textField.textAlignment = NSTextAlignmentLeft;
            textField.clearButtonMode = UITextFieldViewModeWhileEditing;
        }
    }];
    UIAlertAction *action = [UIAlertAction actionWithTitle:[@"确认" S] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSString *text = dialog.textFields.firstObject.text;
        if (complement) {
            complement(text);
        }
    }];
    [dialog addAction:action];
    [dialog addAction:[self creatActionWithTitle:[@"取消" S] complement:nil]];
    [viewController presentViewController:dialog animated:YES completion:nil];
    return dialog;
}
/**
 *  创建默认的按钮
 *
 *  @pram title        按钮标题
 *  @pram complement   点击确认的回调
 */
+ (UIAlertAction *)creatActionWithTitle:(NSString *)title complement:(void(^)(void))complement {
    return [self creatActionWithTitle:title style:UIAlertActionStyleDefault complement:complement];
}
/**
 *  创建按钮
 *
 *  @pram title        按钮标题
 *  @pram style        按钮类型
 *  @pram complement   点击确认的回调
 */
+ (UIAlertAction *)creatActionWithTitle:(NSString *)title style:(UIAlertActionStyle)style complement:(void(^)(void))complement {
    UIAlertAction *action = [UIAlertAction actionWithTitle:title style:style handler:^(UIAlertAction * _Nonnull action) {
        if (complement) {
            complement();
        }
    }];
    return action;
}

#pragma mark - LoadingView
#define LoadingViewDefaultText [@"正在加载中..." S]
+ (instancetype)showLoadingView {
    BaseInfo.dialog = [self loadingViewWithMessage:LoadingViewDefaultText timeInterval:MAXFLOAT];
    return BaseInfo.dialog;
}
+ (void)hiddenLoadingView {
    [BaseInfo.dialog dismissViewControllerAnimated:YES completion:nil];
    BaseInfo.dialog = nil;
}
+ (instancetype)loadingViewWithMessage:(NSString *)message timeInterval:(CGFloat)timeInterval {
    BOOL isTure = [message isEqualToString:LoadingViewDefaultText];
    TYZSystemDialog *dialog = [TYZSystemDialog alertControllerWithTitle:nil message:@"" preferredStyle:UIAlertControllerStyleAlert];
    dialog.view.layer.masksToBounds = YES;
    TYZImageView *imageView =  [[TYZImageView alloc] init];
    [dialog.view addSubview:imageView];
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        if (isTure) {
            make.top.left.equalTo(dialog.view).offset(kWindowWidth / 20);
            make.width.mas_equalTo(imageView.mas_height);
        } else {
            make.centerX.equalTo(dialog.view);
            make.top.equalTo(dialog.view).offset(kWindowWidth / 20);
            make.width.height.mas_equalTo(kWindowWidth / 8);
        }
    }];
    if (isTure) {
        NSMutableArray *imageArray = [NSMutableArray arrayWithCapacity:24];
        NSString *prefix = @"loading_";
        for (int i = 0; i < 24; i ++) {
            UIImage *imgtemp = [UIImage imageNamed:[NSString stringWithFormat:@"%@%d.png", prefix, i]];
            [imageArray addObject:imgtemp];
        }
        imageView.animationImages = imageArray;
        imageView.animationDuration = 1.0;
        imageView.animationRepeatCount = 0;
        [imageView startAnimating];
    } else {
        imageView.image = [UIImage imageNamed:@"Logo"];
    }
    TYZLabel *label =[[TYZLabel alloc] init];
    label.text = message;
    [dialog.view addSubview:label];
    label.numberOfLines = 0;
    label.layer.masksToBounds = YES;
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        if (isTure) {
            make.centerY.equalTo(imageView);
            make.top.equalTo(imageView);
            make.left.equalTo(imageView.mas_right).offset(kWindowWidth / 20);
            make.width.mas_equalTo(kWindowWidth * 0.5);
        } else {
            make.centerX.equalTo(imageView);
            make.top.equalTo(imageView.mas_bottom).offset(kWindowWidth / 40);
            make.width.mas_equalTo(kWindowWidth * 0.7);
        }
    }];
    [dialog.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(label).offset(kWindowWidth / 40);
    }];
    [[self getCurrentViewController] presentViewController:dialog animated:YES completion:^{
        if (timeInterval < 999) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(timeInterval * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [dialog dismissViewControllerAnimated:YES completion:nil];
            });
        }
    }];
    return dialog;
}
#pragma mark - 获取当前窗口的控制器
+ (UIViewController *)getCurrentViewController {
    UIViewController *ctrl = nil;
    UIApplication *app = [TYZApplication sharedApplication];
    if (!ctrl) {
        ctrl = app.keyWindow.rootViewController;
    }
    if (!ctrl) {
        ctrl = [app.windows.firstObject rootViewController];
    }
    if (!ctrl) {
        ctrl = [self viewController];
    }
    if (!ctrl) {
        return nil;
    }
    
    while (!ctrl.view.window && ctrl.presentedViewController) {
        ctrl = ctrl.presentedViewController;
    }
    if (!ctrl.view.window) {
        return nil;
    }
    return ctrl;
}
+ (UIViewController *)viewController {
    UIViewController *currentViewController = nil;
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if ([window subviews].count == 0) return nil;
    if (window.windowLevel != UIWindowLevelNormal) {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for (UIWindow * subWindow in windows) {
            if (subWindow.windowLevel == UIWindowLevelNormal) {
                window = subWindow;
                break;
            }
        }
    }
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    if ([nextResponder isKindOfClass:[UIViewController class]]) {
        currentViewController = nextResponder;
    } else {
        currentViewController = window.rootViewController;
    }
    return currentViewController;
}
#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ([string isEqualToString:@""]) return YES;
    if (textField.text.length + string.length > self.mostLength) {
        [TYZLoadingView showNormal:[[NSString stringWithFormat:@"最多输入%ld个字", (long)self.mostLength] S]];
        return NO;
    }
    return YES;
}
@end
